package com.xuhao.examai.interfaces.controllers;

import com.xuhao.examai.application.services.UserService;
import com.xuhao.examai.application.dto.UserDTO;
import com.xuhao.examai.common.ResultVO;
import com.xuhao.examai.config.JwtTokenUtil;
import com.xuhao.examai.domain.models.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "认证管理", description = "用户认证相关API")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

	private final UserService userService;
	private final AuthenticationManager authenticationManager;
	private final JwtTokenUtil jwtTokenUtil;

	@Operation(summary = "用户登录")
	@PostMapping("/login")
	public ResultVO<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
		String username = loginRequest.get("username");
		String password = loginRequest.get("password");

		// 验证用户名和密码
		Authentication authentication = authenticationManager.authenticate(
				new UsernamePasswordAuthenticationToken(username, password));

		SecurityContextHolder.getContext().setAuthentication(authentication);

		// 生成JWT token
		String token = jwtTokenUtil.generateToken(username);

		// 获取用户信息
		User user = userService.getUserByUsername(username);

		// 更新最后登录时间
		userService.updateLastLoginTime(user.getId());

		// 构建响应数据
		Map<String, Object> response = new HashMap<>();
		response.put("token", token);
		response.put("user", user);

		return ResultVO.success(response);
	}

	@Operation(summary = "用户注册")
	@PostMapping("/register")
	public ResultVO<User> register(@Valid @RequestBody UserDTO userDTO) {
		User user = convertToEntity(userDTO);
		return ResultVO.success(userService.register(user));
	}

	@Operation(summary = "获取当前用户信息")
	@GetMapping("/me")
	public ResultVO<User> getCurrentUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();
		User user = userService.getUserByUsername(username);
		return ResultVO.success(user);
	}

	private User convertToEntity(UserDTO userDTO) {
		User user = new User();
		user.setUsername(userDTO.getUsername());
		user.setPassword(userDTO.getPassword());
		user.setName(userDTO.getName());
		user.setEmail(userDTO.getEmail());
		user.setPhone(userDTO.getPhone());
		user.setRole(userDTO.getRole());
		return user;
	}
}